package com.bms.cfcmms.util;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.util.IntrospectorCleanupListener;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * Created by carl on 2016/4/20.
 */
public class StartSystem implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        servletContext.addListener(IntrospectorCleanupListener.class);

        //配置shiroFilter
        DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
        FilterRegistration.Dynamic filterRegistration = servletContext.addFilter(
                "shiroFilter", delegatingFilterProxy);
        //该值缺省为false,表示生命周期由SpringApplicationContext管理,
        //设置为true则表示由ServletContainer管理
        filterRegistration.setInitParameter("targetFilterLifecycle", "false");
        filterRegistration.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                        DispatcherType.INCLUDE), false, "/*");

        //encodingFilter 编码过滤器
        DelegatingFilterProxy encodingFilterFilterProxy = new DelegatingFilterProxy();
        FilterRegistration.Dynamic encodingFilterRegistration = servletContext.addFilter(
                "encodingFilter", encodingFilterFilterProxy);
        encodingFilterRegistration.setInitParameter("encoding", "UTF-8");
        encodingFilterRegistration.setInitParameter("forceEncoding", "true");
        encodingFilterRegistration.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                        DispatcherType.INCLUDE), false, "/");

        //SpringMVC的servlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet();
        ServletRegistration.Dynamic dynamic = servletContext.addServlet(
                "springMVC", dispatcherServlet);
        dynamic.setInitParameter("contextConfigLocation", "classpath:springMVC-servlet.xml");
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/");
    }
}
